/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Controller;

/**
 *
 * @author Vegard
 */
import java.sql.*;
import java.util.ArrayList;
import Module.*;

public class RoleController {
private Database database = new Database();

    public boolean registerRole(Role role){

        Connection conn = null;
        try{
            conn = DriverManager.getConnection(database.getURL());
            String[] autogen = {"id"};
            PreparedStatement statement = conn.prepareStatement(
                    "Insert into role values(DEFAULT,?)",autogen);
            statement.setString(1, role.getName());
            statement.executeUpdate();
            conn.close();
            return true;
        }catch (Exception e) {
            System.err.println(e);

        }
        return false;
    }
    public boolean editRole(Role role){
        Connection conn = null;
        try{
            conn = DriverManager.getConnection(database.getURL());
            PreparedStatement statement = conn.prepareStatement("Update role "
                    + "set rolename=? where roleId =?");
            statement.setString(1, role.getName());
            statement.setInt(2, role.getId());
            statement.executeUpdate();
            conn.close();
            return true;
        }catch(Exception e){
            System.err.println(e);
        }

        return false;
    }
    public boolean deleteRole(Role role){
        Connection conn = null;
        try{
            conn = DriverManager.getConnection(database.getURL());
            PreparedStatement statement = conn.prepareStatement("delete from role where roleid = ?");
            statement.setInt(1, role.getId());
            statement.executeUpdate();
            conn.close();
            return true;
        }catch(Exception e){
            System.err.println(e);
        }
        return false;
    }

    public ArrayList<Role> getAllRoles(){
        Connection conn = null;
        ArrayList<Role> roles = new ArrayList<Role>();
        try{
            conn = DriverManager.getConnection(database.getURL());
            PreparedStatement statement = conn.prepareStatement("select * from role");
            ResultSet rs = statement.executeQuery();
            while(rs.next()){
                roles.add(new Role(rs.getInt(1),rs.getString(2)));
            }
            conn.close();
            return roles;
            
        }catch(Exception e){
            System.err.println(e);
        }
        return null;
    }
}
